import newhost from "/host.js";
import locales from "/utils/language.js";
import logs from "utils/logs";
const { getSkinSettings } = require('./utils/themeSkin/getSkinSetting');
const { unfinishedTaskFn } = require('./utils/unfinished-task.js');

var QQMapWX = require('/mymap/qqmap-wx-jssdk.min.js');
var qqmapsdk;
var yzFirstlogin = 1;
var yzValidate_page = 1;
let livePlayer = null;
try {
  livePlayer = requirePlugin("live-player-plugin");
} catch (error) {
  
}

var loginTap = false;
// var loginTap = false;
App({
  data: {
    // wx_token: ''
    host: newhost.host,
    uniacid: newhost.uniacid,
    store_id: newhost.store_id,
    basic_info: {},
    validate_page: {},
    front_accept_message_id: "wx446c12387876992d", //后屏幕小程序appdid
    front_mini_programs_id: "wxf90477356b51ec91",
    accept_message_id: "wxa0ecf1f5513abab3", //前屏幕小程序appdid
    mini_programs_id: "wxf90477356b51ec91",
    clearlogin: null,

    login_type: 1, //1无请求，2正在请求 状态锁
    login_fun_list: [], // 需要登录后再请求的接口队列
    address_code:"",
    authPageShow:false,
    
  },
  onLaunch(options) {
    
    
    wx.onNeedPrivacyAuthorization((resolve, eventInfo) => {
        console.log('触发本次事件的接口是：' + eventInfo.referrer)
        // 需要用户同意隐私授权时
        // 弹出开发者自定义的隐私授权弹窗
        // this.setData({
        // showPrivacy: true
        // })
        if(this.data.authPageShow){
          wx.showModal({
            title: '提示',
            content: '需要使用完整功能需要跳转同意用户隐私协议',
            complete: (res) => {
              if (res.confirm) {
                this.data.authPageShow = false;
                this.globalData.resolvePrivacyAuthorization = resolve;
                wx.navigateTo({
                  url: '/mircoApp/authorizationPage/authorizationPage',
                })
              }
            }
          })
          return
        }
        this.globalData.resolvePrivacyAuthorization = resolve;
        wx.navigateTo({
          url: '/mircoApp/authorizationPage/authorizationPage',
        })
        console.log(this.globalData.resolvePrivacyAuthorization,'resolvePrivacyAuthorization',this.data.authPageCount)
    })
    let that = this;
    wx.getSystemInfo({
      success: (res) => {
        this.globalData.statusBarHeight = res.statusBarHeight;
        this.globalData.navBarHeight = 44 + res.statusBarHeight;
      },
    });
    this._getLanguage(locales);

    this.globalData.vid = null;
    // this.globalData.table_id = null;
    // if (options.query.scene) {
    //   let scene = decodeURIComponent(options.query.scene);
    //   if (scene) {
    //     var info_arr = [];
    //     info_arr = scene.split(',');
    //     let storeTable = {};//企业餐桌号扫码
    //     for (let i = 0; i < info_arr.length; i++) {
    //       let chil_arr = [];
    //       chil_arr = info_arr[i].split('=');
    //       if (chil_arr[0] == 'ta_id') {
    //         this.globalData.table_id = chil_arr[1];
    //       }
    //     }
    //   } 
    // }else{
    //   this.globalData.table_id = null
    //   wx.removeStorageSync("storeTable");
    // }
    // console.log(this.globalData.table_id)
    //删除首次模板信息
    try {
      //  每次关闭要清除存储
      wx.removeStorageSync("tempIndex");
      wx.removeStorageSync("iPhoneBottom");
      wx.removeStorageSync("deliverId");
      wx.removeStorageSync("storeTable");
    } catch (e) {
      // Do something when catch error
    }

    //记录首次进入小程序页面
    try {
      if (options.query) {
        console.log(options, 'options1');
        this.seyzredirect(options.path, options.query);
        // 抽取成seyzredirect方法
        // let query = options.query;
        // //参数多时通过&拼接url的参数
        // var urlWithArgs = options.path + "?";
        // for (var key in query) {
        //   var value = query[key];
        //   urlWithArgs += key + "=" + value + "&";
        // }
        // urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1);
        // wx.setStorageSync("yz_redirect", `${urlWithArgs}`);
        if (options.query.store_alone_id) {
          // 如果有store_alone_id,进入企业独立模块
          this.globalData.STORE_ID = options.query.store_alone_id;
          this.globalData.store_alone_temp = 1;
        }
        if (options.query.dyID) {
          //deliverId 获取链接上的参数，自提点id
          this.setDeliver(options);
        }
      } else {
        // wx.setStorageSync("yz_redirect", options.path);
        this.seyzredirect(options.path);
      }

    } catch (e) {
      console.log(e);
    }
    //隐藏底部菜单栏
    // wx.hideTabBar({})

    // try {
    // 	wx.removeStorageSync('withdraw_status')
    // } catch (e) {
    // 	// Do something when catch error
    // }
    logs.info('----------app.js->onLaunch->options.scene-----------',options.scene)
    if (options.query.mid) {
      this._setMid(options.query.mid);
    }
    logs.info('----------app.js->onLaunch->options.query-----------',options.query)
    // if (options.query && options.query.scene) {
    //   let scene = decodeURIComponent(options.query.scene);
    //   logs.info('----------app.js->onLaunch->options.query.scene-----------',scene)
    //   if (scene) {
    //     let info_arr = [];
    //     info_arr = scene.split(',');
    //     for (let i = 0; i < info_arr.length; i++) {
    //       let chil_arr = [];
    //       chil_arr = info_arr[i].split('=');
    //       if (chil_arr[0] == 'mid') {
    //         this._setMid(chil_arr[1]);
    //       }
    //     }
    //   }
    // }
    if(this.globalData.mid == 0){
      if(wx.getStorageSync('mid')){
        this.globalData.mid = wx.getStorageSync('mid')
      }
    }
    this.gotochecklogin(options);
    this.getSystemInfo();
    try {
      //获取青蛙相关信息
      wxfaceapp.checkWxFacePayOsInfo({
        success(res) {
          console.log("1111111::::::", res.screenInfo);
          if (res.screenInfo == "back-screen") {
            wxfaceapp.onRemoteMessage(function (resdata) {
              if (resdata.content) {
                let content = JSON.parse(resdata.content);
                if (content.redirectType) {
                  if (content.redirectType == "succeededPayment") {
                    wx.redirectTo({
                      url: "/packageC/frogpro/succeededPayment/succeededPayment?money=" + content.money,
                    });
                  } else if (content.redirectType == "login") {
                    wx.redirectTo({
                      url: "/packageC/frogpro/backScreenlogin/backScreenlogin",
                    });
                  } else if (content.redirectType == "lose") {
                    wx.redirectTo({
                      url: "/packageC/frogpro/lose/lose?money=" + content.money,
                    });
                  } else if (content.redirectType == "waitingPayment") {
                    wx.redirectTo({
                      url: "/packageC/frogpro/waitingPayment/waitingPayment?money=" + content.money,
                    });
                  }
                }
              }
            });
            that.startLogin();
          }
        },
        fail(res) {},
      });
    } catch (e) {
      //TODO handle the exception
    }
    console.log(this.globalData.STORE_ID, 'STORE_ID=============>>>>>>>>>>');
    this.overShare();

    if(wx&&wx.setInnerAudioOption){
      wx.setInnerAudioOption({
        obeyMuteSwitch: false,
        // 解决小程序createInnerAudioContext()音频播放iOS端真机调试没有声音问题
        success: function (res) {
          console.log("开启静音模式下播放音乐的功能");
        },
  
        fail: function (err) {
          console.log("静音设置失败");
        },
      });
    }
  },
  /**
   * url 请求地址
   * data 请求的参数
   * success 成功的回调
   * fail 失败的回调
   * complete 结束的回调函数（调用成功、失败都会执行）
   */
  _getNetWork: function (_ObjData) {
    return this._Request(_ObjData, 'GET');
  },
  /**
   * url 请求地址
   * success 成功的回调
   * fail 失败的回调
   * complete 结束的回调函数（调用成功、失败都会执行）
   */
  _postNetWork: function (_ObjData) {
    return this._Request(_ObjData, 'POST');
  },
  _Request(obj, method) {
    return new Promise((resolve, reject) => {
      obj.resolve = resolve;
      obj.reject = reject;
      obj.method = method;
      //1就发起第一次请求，2加入队列数组
      if (this.data.login_type == 1) {
        this.toRequestNetWork(obj);
      } else {
        this.data.login_fun_list.push(obj);
      }
    });
  },

  toRequestNetWork(_ObjData) {
    var url = _ObjData.url;
    var resolve = _ObjData.resolve;
    var reject = _ObjData.reject;
    var method = _ObjData.method;
    var data = _ObjData.data || {};
    let params = _ObjData.data;
    var success = _ObjData.success;
    var fail = _ObjData.fail;
    var complete = _ObjData.complete;
    var validateBol = _ObjData.validateBol == 2 ? false : true;
    // 加载遮罩
    var showToastIn = true;
    if (typeof _ObjData.showToastIn == "boolean") {
      showToastIn = _ObjData.showToastIn;
    }

    var that = this;
    if (showToastIn) {
      wx.showNavigationBarLoading();
    }

    let _session = "";
    let _wx_token = "";
    try {
      let value = wx.getStorageSync("session");
      if (value) {
        _session = value;
      }
    } catch (e) {
      console.log(e);
    }
    try {
      let value = wx.getStorageSync("wx_token");
      if (value) {
        _wx_token = value;
      }
    } catch (e) {
      console.log(e);
    }

    if (yzFirstlogin === 0 && yzValidate_page === 1) {
      if(data.not_validate_page == '0' && data){
        //想接口不返回validate_page的参数
      }else{
        url += "&validate_page=1";
      }
    }

    if ((yzFirstlogin === 1 && url.indexOf("member.login.index") < 0 && url.indexOf("member.member.wxJsSdkConfig") < 0 && url.indexOf("privacy-policy.index") < 0 ) || url.indexOf("finance.income-page.index") >= 0) {
      url += "&basic_info=1&validate_page=1";
    }
    if(url.indexOf("home-page.index") > 0){
      url += "&scope=home";
    }

    if (method === 'GET' && params) {
      let paramsArray = [];
      Object.keys(params).forEach(key =>
        paramsArray.push(key + "=" + params[key])
      );
      url += "&" + paramsArray.join("&");
    }

    url += "&app_type=wechat";
    url += "&3rd_session=" + _session;

    if (this.globalData.store_alone_temp == 1) {
      // 开启企业独立模块
      url += "&store_id=" + this.globalData.STORE_ID;
    }
    console.log(method, "请求中Url:", url);

    let headers = {
      "Content-Type": "application/json",
      Accept: "application/json",
      Cookie: "PHPSESSID=" + _wx_token,
    };

    if (this.globalData.new_page_comeIn != 2) {
      let pages = getCurrentPages();
      let view = pages[pages.length - 1];
      // 浏览足迹  new_page_comeIn == 2为页面第一个请求接口
      headers['local-url'] = view.route;
      this.globalData.new_page_comeIn = 2;
    }

    url += "&mini_version=v1.1.149";
    this.data.login_type = 2;
    wx.request({
      url: url,
      method: method,
      data: data,
      header: headers,
      timeout: 10000,
      success: (res) => {
        if (res.data.basic_info) {
          getSkinSettings({themeBaseColor: res.data.basic_info.theme_color});
          yzFirstlogin = 0;
          that.data.basic_info = res.data.basic_info;
          that.initLanguage(that.data.basic_info.lang);
          if(res.data.basic_info.host) that.globalData.imgPath = res.data.basic_info.host;//线上图片存储位置
          try {
            wx.setStorageSync("yz_basic_info", res.data.basic_info);
            wx.setStorageSync("ios_virtual_pay", res.data.basic_info.globalParameter.ios_virtual_pay);
            // 判断企业独立模块是否开启
            let basic_info = res.data.basic_info;
            if (basic_info.plugin_setting && basic_info.plugin_setting.store_alone_temp && basic_info.plugin_setting.store_alone_temp.enable == 1) {
              this.globalData.store_alone_temp = 1;
              let pages = getCurrentPages(),
                view = pages[pages.length - 1]; //获取当前页面的对象
              if (!this.globalData.STORE_ID && view.route !== 'packageG/independent_store/index/index') {
                if(view.route == 'packageA/detail_v2/detail_v2' && res.data.data.goods_type == 'store_goods' && res.data.data.get_store_info){
                  this.globalData.STORE_ID = res.data.data.get_store_info.store_id;
                }else{
                  this.isHasStoreId();
                }
              }
            }

            this.globalData.cart_num = res.data.basic_info.globalParameter ? res.data.basic_info.globalParameter.cart_num : '';
            if (res.data.basic_info.lang && res.data.basic_info.lang.member_center) {
              // 积分名称
              wx.setStorageSync('integral', res.data.basic_info.lang.member_center.credit1 || '积分');
            }
            if (res.data.basic_info.lang && res.data.basic_info.lang.member_center) {
              // 余额名称
              wx.setStorageSync('balance',res.data.basic_info.lang.member_center.credit || '余额')
            }
          } catch (e) {
            console.log("yz_basic_info存储出错", e);
          }
          try {
            if (res.data.basic_info.home.plugin.new_member_prize && res.data.basic_info.home.plugin.new_member_prize.prize && res.data.basic_info.home.plugin.new_member_prize.prize.length != 0) {
              console.log("storage_newAward存储====");
              wx.setStorageSync("storage_newAward", res.data.basic_info.home.plugin.new_member_prize);
            }
          } catch (e) {
            console.log("storage_newAward存储出错", e);
          }
        }
        if (validateBol && res.data.validate_page) {
          that.getInvite(res.data.validate_page);
        }
        if (res.data.result == 0 && res.data.msg === "请登录") {
          that.login_state(_ObjData, "get");
          return;
        }
        if(res.data.result == 0 && !that._isTextEmpty(res.data.data)){
          that.taskRoute(res);
        }
        if (res.data.result == 2) {
          wx.removeStorage({
            key: "session",
            success: function (res) {
              console.log(res.data);
            },
          });
          wx.removeStorage({
            key: "openid",
            success: function (res) {
              console.log(res.data);
            },
          });
          wx.removeStorage({
            key: "wx_token",
            success: function (res) {
              console.log(res.data);
            },
          });
          wx.removeStorage({
            key: "userInfo",
            success: function (res) {
              that._getNetWork(_ObjData);
            },
          });
        } else {
          // wx.hideToast()
          wx.hideNavigationBarLoading();
          success && success(res);
          resolve(res);
          this.data.login_type = 1;
          if (this.data.login_fun_list.length > 0) {
            let obj = this.data.login_fun_list.shift();
            if(data.isnolist == 1){
              // 传参有这个就不要去重启队列
              return
            }
            this.toRequestNetWork(obj);
            // console.log(obj,"-------------------------------------------------success")
          }
        }
      },
      fail: (res) => {
        this.data.login_type = 1;
        if (fail && typeof fail === "function") {
          fail(res);
        }
        reject(res);
        // wx.showToast({
        //   title: "数据获取失败！",
        //   icon: "loading",
        //   duration: 2000,
        //   mask: true,
        // });
        this.toRequestNetWork(_ObjData)
        logs.error('----------app.js->wx.request->fail-----------',res,url)
        console.log("数据获取失败:", url, res);
      },
      complete: (res) => {
        if (complete && typeof complete === "function") {
          complete(res);
        }
      },
    });
  },
  taskRoute(res){
    if(res.data.result == 0 && (res.data.data.task_package_invite_code == -1 || res.data.data.task_package_real_name_auth == -1)){
      if(res.data.data.task_package_invite_code == '-1'){
        wx.navigateTo({
          url: '/packageI/taskPackage/middle/middle',
        })
      }
      if(res.data.data.task_package_real_name_auth == '-1'){
        var pages = getCurrentPages(); //获取加载的页面
        var currentPage = pages[pages.length - 1]; //获取当前页面的对象
        let routeData = currentPage.route;
        wx.setStorageSync("real_name_redirect", routeData);
        wx.navigateTo({
          url: '/packageH/signPage/personBank/personBank?from=bindRealName',
        })
      }
    }
  },
  /*青蛙pro信息*/
  requestFrogproServerData(url, method, data) {
    return new Promise(function (resolve, reject) {
      wx.request({
        url: url,
        data: data,
        header: {
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        method: method,
        success: function (res) {
          resolve(res);
        },
        fail: function (res) {
          reject(res);
        },
      });
    });
  },
  // 青蛙小程序登录
  startLogin: function () {
    let that = this;
    that.data.clearlogin = setInterval(function () {
      wx.login({
        success: function (_json) {
          if (_json.code) {
            // 请求登录接口
            that
              .requestFrogproServerData(that.getFrogproNetAddresss("member.login.index"), "get", {
                code: _json.code,
                ver: "2",
                // info: _info
              })
              .then(function (res) {
                var _data = res.data;
                if (_data.result == 1) {
                  // 存储key
                  if (_data.data.user_info) {
                    wx.setStorageSync("nickname", _data.data.user_info.nickname);
                  }
                  if (_data.msg.session) {
                    wx.setStorageSync("session", _data.session);
                  }
                  if (_data.msg.wx_token) {
                    wx.setStorageSync("wx_token", _data.wx_token);
                  }
                  if (_data.data.store) {
                    wx.setStorageSync("storeMessage", _data.data.store);
                  }
                  let Json = {
                    wx_token: _data.msg.wx_token,
                    session: _data.msg.session,
                    store_id: _data.data.store.store_id,
                    dispatch_type_id: 2,
                    goods_id: _data.data.store.goods_id,
                    host: that.data.host,
                    uniacid: that.data.uniacid,
                  };
                  wxfaceapp.postMsg({
                    targetAppid: that.data.accept_message_id,
                    content: JSON.stringify(Json),
                    success(res) {},
                    fail(res) {},
                  });
                } else {
                  console.log("错误信息:::" + res.errMsg);
                }
                // 异步请求到的数据data
              })
              .catch(function (res) {
                console.log("错误信息:::" + res.errMsg);
              });
          } else {
            console.log("错误信息:::" + res.errMsg);
          }
        },
        fail: function (res) {
          console.log("登录失败，请求被拒绝！获取用户登录态失败！" + res);
        },
      });
    }, 600000);
  },
  getFrogproNetAddresss: function (action) {
    let wx_token = this.getWxToken();
    var url = this.data.host + "/addons/yun_shop/api.php?i=" + this.data.uniacid + "&session_id=" + wx_token + "&type=12&route=" + action;
    return url;
  },
  /*青蛙pro信息*/
  //获取设备信息
  getSystemInfo() {
    try {
      const res = wx.getSystemInfoSync();
      let model = res.model;
      if (/iPhone X/i.test(model) || /iPhone 11/i.test(model) || /iPhone 12/i.test(model) || /iPhone 13/i.test(model) || /iPhone 14/i.test(model)) {
        try {
          wx.setStorageSync("iPhoneBottom", model);
        } catch (e) {
          console.log(e);
        }
      }
    } catch (e) {
      // Do something when catch error
    }
  },
  onShow(options) {
    // 页面出现在前台时执行
    // this.getInvite();
    
    yzFirstlogin = 1;
    yzValidate_page = 1;
    this.data.login_type = 1;
    if(options.query && options.query.custom_params) {
      this._setMid(JSON.parse(decodeURIComponent(options.query.custom_params)).mid);
    }
    const sceneList = [1007, 1008, 1014, 1044, 1045, 1046, 1047, 1048, 1049, 1073, 1154, 1155]
    // 分享卡片入口场景才调用getShareParams接口获取以下参数
    if(options.scene == 1038){
      this.globalData.AppScene = options.scene;
      this.globalData.cloud_pay_extraData = options.referrerInfo?.extraData?.success || false;
    }
    if (livePlayer && sceneList.indexOf(options.scene) > -1) {
      livePlayer
        .getShareParams()
        .then((res) => {
          console.log('get room id', res.room_id) // 房间号
          // console.log('get openid', res.openid) // 用户openid
          // console.log('get share openid', res.share_openid) // 分享者openid，分享卡片进入场景才有
          console.log("get custom params", res.custom_params); // 开发者在跳转进入直播间页面时，页面路径上携带的自定义参数，这里传回给开发者
          this._setMid(res.custom_params.mid);
        })
        .catch((err) => {
          console.log("get share params", err);
        });
    }
    if(options.referrerInfo && options.referrerInfo.extraData) {
      this.globalData.integralOtherMiniData = options.referrerInfo.extraData || {};
    }
    if (options.query.store_alone_id) {
      // 如果有store_alone_id,进入企业独立模块
      this.globalData.STORE_ID = options.query.store_alone_id;
      this.globalData.store_alone_temp = 1;
    }
    logs.info('----------app.js->onShow->onShow.scene-----------',options.scene)
    logs.info('----------app.js->onShow->onShow.options.query-----------',options.query)
    this.globalData.loginScene.scene = options.scene;
    if (options.query && options.query.scene) {
      let scene = decodeURIComponent(options.query.scene);
      logs.info('----------app.js->onShow->options.query.scene-----------',scene)
      this.globalData.loginScene.scene_to = scene;
      if (scene) {
        let info_arr = [];
        info_arr = scene.split(',');
        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split('=');
          if (chil_arr[0] == 'mid') {
            this._setMid(chil_arr[1]);
          }
        }
      }

      wx.removeStorageSync("storeTable");
      this.globalData.table_id = null;
    }
    if(this.globalData.mid == 0){
      if(wx.getStorageSync('mid')){
        this.globalData.mid = wx.getStorageSync('mid')
      }
    }
    this._getTemplate();
  },
  onHide() {
    if(this.globalData.CityPageADCode) this.globalData.CityPageADCode = null;
    // 会员的弹窗广告
    wx.removeStorageSync("firstAdvertisement");
    // 首页的弹窗广告
    wx.removeStorageSync("fullAdvertisement");
    wx.removeStorageSync("popAdvertisement");
    //装修的弹窗广告
    wx.removeStorageSync("page_idFull_screens");
    wx.removeStorageSync("page_idAdvertisings");
    // 关闭时删除Storage的地址
    wx.removeStorageSync("address-point");

    // 新装修数据
    wx.removeStorageSync("home_onUnload");
    wx.removeStorageSync("new_decorate");
    //wx.removeStorageSync("storeTable");
  },
  seyzredirect(path, options) {
    // 设置当前链接  登录后返回
    console.log(path, options, 'options2');
    var pages = getCurrentPages(); //获取加载的页面
    var currentPage = pages[pages.length - 1]; //获取当前页面的对象
    // 优先级 options > currentPage.options  当只有path参数传入即不用options
    let optionsData = options ? options : (path ? '' : currentPage.options);
    let routeData = path ? path : currentPage.route;
    let notLogin = ['pages/login/login', 'packageA/member/editmobile/editmobile'];
    if (notLogin.indexOf(routeData) > -1) {
      return;
    }
    if (optionsData) {
      //参数多时通过&拼接url的参数
      var urlWithArgs = routeData + "?";
      for (var key in optionsData) {
        var value = optionsData[key];
        urlWithArgs += key + "=" + value + "&";
      }
      urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1);
      wx.setStorageSync("yz_redirect", `${urlWithArgs}`);
    } else {
      wx.setStorageSync("yz_redirect", routeData);
    }

    // console.log(optionsData,routeData, 'options3')
  },
  getyzredirect() {
    let yzredirect = "";
    try {
      let value = wx.getStorageSync("yz_redirect");
      if (value) {
        yzredirect = value;
      }
    } catch (e) {
      console.log(e);
    }
    return yzredirect;
  },
  globalData: {
    params: null,//用于当小程序跳转页面需要传递多个参数，在接收页面中使用 app.globalData.params 获取
    host: newhost.host,
    uniacid: newhost.uniacid,
    new_page_comeIn: 0,
    statusBarHeight: 0,
    screenHeight: 0,
    define_order_pay: 1, // '确认付款' => 1,这种方法定义常量不用每个js都注入
    define_order_receiv: 5, // '确认收货' => 5,这种方法定义常量不用每个js都注入
    define_order_check: 8, // '查看物流' => 8,这种方法定义常量不用每个js都注入
    define_order_cancle: 9, // '取消订单' => 9,这种方法定义常量不用每个js都注入
    define_order_comment: 10, // '评价' => 10,这种方法定义常量不用每个js都注入
    define_order_recomment: 11, // '追加评价' => 10,这种方法定义常量不用每个js都注入
    define_order_delete: 12, // '删除订单' => 10,这种方法定义常量不用每个js都注入
    define_order_refund: 13, // '退款' => 10,这种方法定义常量不用每个js都注入
    define_order_used: 14, // '确认使用' => 10,这种方法定义常量不用每个js都注入
    // uid: 0,// 推广人id
    mid: 0,
    userInfo: null,
    globaSession: null,
    // 自定义跳转方式选择值,用于区别调用跳转方法
    tabBar: {
      index: "-1",
      category: "-1",
      extension: "-1",
      cart: "-1",
      memindex: "-1",
    },
    // 腾讯地图key值
    qqmapkey: "",
    // 腾讯地图校验码
    qqmapsig: "",
    pathData: "",
    cart_num: 0, //购物车数量
    isLocationIng: false,

    // 企业独立模块
    store_alone_temp: 0,
    STORE_ID: 0,
    integralOtherMiniData: {},
    beforeBindMobilePage: '',//绑定手机、邀请码页面跳转前路径
    phone_bill_recharge_type: true, //话费充值 提示弹窗

    imgPath: newhost.host + '/static/local/',//线上链接图片存储路径，默认当前域名下的/static/local/
    // imgPath: '',
    // imgPath: 'https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/',
    AppScene:'',//小程序场景值
    cloud_pay_extraData:false,//是否从云汇算第三方小程序回来
    // scene进入小程序的场景值，scene_to打开小程序携带的参数
    loginScene:{scene:'',scene_to:''},
  },
  _getLanguage(data) {
    wx.setStorageSync("langIndex", data);
  },
  _getTemplate() {
    // 获取动态腾讯地图key
    let urlStr = this.getNetAddresss("plugin.min-app.Frontend.Controllers.page.index");
    urlStr = urlStr + "&scope=pass";
    return new Promise((resolve, reject) => {
      wx.request({
        url: urlStr,
        method: "GET",
        header: {
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        data: {
          login_param:this.globalData.loginScene
        },
        success: (resdata) => {
          let res = resdata.data;
          if (res.result === 1) {

            this.globalData.qqmapkey = res.data.qq_map_web_key;
            this.globalData.qqmapsig = res.data.qq_map_web_sign;
            try {
              // 平台协议
              wx.setStorageSync("new_agreement", {
                agreement_name: res.data.agreement_name,
                new_agreement: res.data.new_agreement,
                theme_color:res.data.theme_color
              });
            } catch (error) {
              console.log(error);
            }
            resolve();
          } else {
            this.globalData.qqmapkey = "KUBBZ-IXPCO-3ZNWD-SHC4H-O4TZH-ZSBQR";
            this.globalData.qqmapsig = "l3Fyt4WylOFiPzbBSIkjWJ1aDU6NNa4";
            resolve();
          }
        },
        fail: (res) => {
          this.globalData.qqmapkey = "KUBBZ-IXPCO-3ZNWD-SHC4H-O4TZH-ZSBQR";
          this.globalData.qqmapsig = "l3Fyt4WylOFiPzbBSIkjWJ1aDU6NNa4";
          resolve();
        }
      });
    });
  },

  _setMid: function (mid) {
    this.globalData.mid = mid;
    logs.info('----------app.js->_setMid->mid-----------',mid)
    wx.setStorage({
      key: "mid",
      data: mid,
    });
  },
  _setshopid: function (shop_id) {
    this.globalData.shop_id = shop_id;
    wx.setStorage({
      key: "shop_id",
      data: shop_id,
    });
  },
  _setvid: function (vid) {
    this.globalData.vid = vid;
  },
  _setcircleInvitationId(circle_invitation_id) {
    console.log("设置了circle_invitation_id");
    this.globalData.circle_invitation_id = circle_invitation_id;
  },
  _setroomid: function (roomid) {
    this.globalData.roomid = roomid;
  },
  _setshareRoomID: function (share_room_id) {
    this.globalData.share_room_id = share_room_id;
  },

  isHasStoreId() {
    let urlStr = this.getNetAddresss("plugin.store-alone-temp.frontend.home.history-store");
    this._getNetWork({
      url: urlStr,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          this.globalData.STORE_ID = res.data.store_id || 0;
          if (!this.globalData.STORE_ID) {
            // 没有企业id就跳转提示页
            wx.reLaunch({
              url: '/packageG/independent_store/access_tip/access_tip',
            });
          } else {
            // 有就跳首页
            wx.reLaunch({
              url: '/packageG/independent_store/index/index?store_id=' + this.globalData.STORE_ID,
            });
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1500,
            success: (res) => {
              setTimeout(() => {
                wx.reLaunch({
                  url: '/packageG/independent_store/access_tip/access_tip',
                });
              }, 1200);
            }
          });
        }
      }
    });
  },

  getWxToken: function () {
    var value = wx.getStorageSync("wx_token");
    if (value) {
      console.log("同步token", value);
      return value;
    } else {
      console.log("获取token失败");
    }
  },

  getNetAddresss: function (action) {
    // let wx_token = this.getWxToken();
    this.getExtJson();
    let store_id = newhost.store_id;
    var url = this.data.host + "/addons/yun_shop/api.php?i=" + this.data.uniacid + "&type=2&route=" + action;
    if(store_id){
      url += `&is_store=1`
    }

    if (this.globalData.mid) {
      url += "&mid=" + this.globalData.mid;
    }
    if (this.globalData.vid) {
      url += "&vid=" + this.globalData.vid;
    }
    if (this.globalData.circle_invitation_id) {
      console.log("地址带上circle_invitation_id");
      url += "&circle_invitation_id=" + this.globalData.circle_invitation_id;
    }
    if (this.globalData.roomid) {
      url += "&room_id=" + this.globalData.roomid;
    }
    if (this.globalData.shop_id) {
      url += "&shop_id=" + this.globalData.shop_id;
    }
    url += "&ingress=weChatApplet";

    if (url.indexOf("member.login.index") > -1) {
      // 解决登录授权后没有新人奖（basic_info ）
      yzFirstlogin = 1;
      url += "&store_id=" + this.data.store_id;
    }
    // url += "&mid=399"
    console.log("APP____URL:::", url);
    return url;
  },
  // 时间戳差值
  getTimeDifference(Timestamp) {
    var now = Date.parse(new Date());
    // console.log("Timestamp", Timestamp);
    let time = Timestamp < 1000000000000 ? Timestamp * 1000 : Timestamp;
    // console.log(time - now);
    if (time - now > 0) {
      return time - now;
    } else if (time - now <= 0) {
      return 0;
    }
  },

  // 返回评价数组
  getEvaluate: function (num) {
    return {
      num: num,
      list: [1, 1, 1, 1, 1, 0, 0, 0, 0, 0].slice(5 - num, 10 - num),
    };
  },
  // 判断是否是空
  _isTextEmpty: function (str) {
    if (str == null || str == "" || str == undefined) {
      return true;
    } else {
      return false;
    }
  },
  // 判断ios还是android
  isIosOrAndroid: function () {
    let u = navigator.userAgent;
    let isAndroid = u.indexOf("Android") > -1 || u.indexOf("Adr") > -1; // android终端
    let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); // ios终端
    let isStr = "";
    if (isAndroid) {
      isStr = "android";
    }
    if (isiOS) {
      isStr = "ios";
    }
    return isStr;
  },
  // 判断参数传递是否为空
  setMailLanguage: function (defaultStr, languageStr) {
    let language = this._isTextEmpty(languageStr) ? defaultStr : languageStr;
    return language;
  },
  // 是否手机
  _isMoblie: function (value) {
    // return !/^1(3|5|7|8|9)[0-9]{9}$/.test(value)
    return isNaN(Number(value));
  },
  // 判断URL链接中是否有mid如果有
  _isMid: function (url, val) {
    if (url.indexOf("mid=") >= 0) {
      return this.changeUrlArg(url, "mid", val);
    } else {
      let burl = this.delQueStr(url, "mid");
      return this.changeUrlArg(burl, "mid", val);
    }
  },
  changeUrlArg: function (url, arg, val) {
    var pattern = arg + "=([^&]*)";
    var replaceText = arg + "=" + val;
    return url.match(pattern) ? url.replace(eval("/(" + arg + "=)([^&]*)/gi"), replaceText) : url.match("[?]") ? url + "&" + replaceText : url + "?" + replaceText;
  },
  // 删除参数值
  delQueStr: function (url, ref) {
    var str = "";
    if (url.indexOf("#") != -1) {
      str = url.substr(url.indexOf("#") + 1);
    } else {
      return url;
    }
    var arr = "";
    var returnurl = "";
    if (str.indexOf("&") != -1) {
      arr = str.split("&");
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].split("=")[0] != ref) {
          returnurl = returnurl + arr[i].split("=")[0] + "=" + arr[i].split("=")[1] + "&";
        }
      }
      return url.substr(0, url.indexOf("?")) + "?#" + returnurl.substr(0, returnurl.length - 1);
    } else {
      arr = str.split("=");
      if (arr[0] == ref) return url.substr(0, url.indexOf("?"));
      else return url;
    }
  },
  getExtJson: function () {
    console.log("================enter extJson===============");
    var that = this;
    var extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {};
    console.log("********extConfig*********", extConfig);
    if (extConfig.host) {
      console.log("================extJson exists===============");
      that.data.host = extConfig.host;
      that.data.uniacid = extConfig.uniacid;
    } else {
      console.log("================extJson not exists===============");
      wx.getExtConfigSync({
        success: function (res) {
          console.log("================extJson11===============", res.extConfig);
          that.data.host = res.extConfig.host;
          that.data.uniacid = res.extConfig.uniacid;
        },
        fail: function (res) {
          console.log("================error.extJson11===============", res);
        },
      });
    }
  },

  //是否开启邀请页面
  async getInvite(data) {
    wx.setStorageSync('validate_page', data)
    let pages = getCurrentPages(); //获取加载的页面
    let currentPage = pages[pages.length - 1]; //获取当前页面的对象
    let routeData = currentPage.route;
    if ((data.is_invite === 1 || data.invite_mobile === 1) && (data.real_name_auth_is_open === 0 || (data.real_name_auth_is_open === 1 && data.is_auth === 1)) && (data.bind_address && data.bind_address.is_bind_address == 1) && data.is_level_compel == 0) {
      yzValidate_page = 0;
    }
    if(routeData == 'mircoApp/authorizationPage/authorizationPage') return;
    if(routeData !== 'packageG/missionCenter/missionCenter') unfinishedTaskFn(data,this);//处理一些需要跳转页面的业务逻辑（绑定手机、邀请码等等）
  },

  setBeforeBindMobilePage(){
    // 记录绑定手机调整前页面路径
    let pages = getCurrentPages(); //获取加载的页面
    let currentPage = pages[pages.length - 1]; //获取当前页面的对象
    let routeData = currentPage.route;
    // 上一个页面是扫描二维码进来的 参数一起带过去
    if(currentPage.options && currentPage.options.scene){
      this.globalData.beforeBindMobilePage = routeData+'?scene='+currentPage.options.scene;
      return
    }else if(currentPage.options && !currentPage.options.scene){
      let obj = Object.keys(currentPage.options);
      if(obj.length>0){
        // 有参数才走，没参数直接赋值路径
        obj.forEach((ele,ind) => {
          if(ind == 0){
            this.globalData.beforeBindMobilePage += `${routeData}?${ele}=${currentPage.options[ele]}`
          }else{
            this.globalData.beforeBindMobilePage += `&${ele}=${currentPage.options[ele]}`
          }
        });
      }else{
        this.globalData.beforeBindMobilePage = routeData;
      }
    }
  },
  
  requestServerData(url, method, data) {
    return new Promise( (resolve, reject)=> {
      wx.request({
        url: url,
        data: data,
        header: {
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        method: method,
        success: (res)=> {
          resolve(res);
          if (url.indexOf('member.login.index') > -1 && this.data.login_type == 2) {
            console.log('登录接口,并且走过静默登录result=0,this.data.login_type = 2');
            //静默=>授权登录=>登录成功=>重启队列
            if(res.data.result){
              this.data.login_type = 1;
              console.log(this.data.login_type,'login_fun_list')
            }
          }
        },
        fail: function (res) {
          reject(res);
        },
      });
    });
  },
  login_state(ObjData) {
    //接口返回0，并且未登录的情况处理x
    var that = this;
    this.globalData.phone_bill_recharge_type = true;
    wx.login({
      success: (_json) => {
        wx.showLoading({
          title: "自动登录中....",
        });
        if (_json.code) {
          // 请求登录接口查看是否有登陆过
          that
            .requestServerData(that.getNetAddresss("member.login.index"), "get", {
              code: _json.code,
              ver: "2",
              login_param:this.globalData.loginScene
            })
            .then((res) => {
              wx.hideLoading();
              var _data = res.data;
              if (_data.result == 1) {
                that.data.login_type = 1;
                if (_data.data.session) {
                  wx.setStorageSync("session", _data.data.session);
                }
                if (_data.data.user_info) {
                  wx.setStorageSync("nickname", _data.data.user_info.nickname);
                }
                wx.setStorage({
                  key: "openid",
                  data: _data.data.openid,
                });
                if (_data.data.wx_token) {
                  wx.setStorageSync("wx_token", _data.data.wx_token);
                }
                wx.setStorage({
                  key: "yz_uid",
                  data: _data.data.uid,
                });
                wx.removeStorageSync("new_decorate"); //登录之后清除首页缓存数据重新请求
                console.log("登录后", _data,this.globalData.loginScene);
                logs.info('----------app.js->login_state->登录的会员id和设置的mid-----------',_data.data.uid,this.globalData.mid)
                if (ObjData.method == 'POST') {
                  that._postNetWork(ObjData);
                } else {
                  that._getNetWork(ObjData);
                }
              } else {
                that.data.login_type = 2;
                that.data.login_fun_list = [];
                // this.data.login_fun_list.push(ObjData)
                // this.data.login_fun_list.unshift(ObjData)
                console.log(this.data.login_fun_list)
                that.seyzredirect();
                wx.showModal({
                  title: "提示",
                  content: _data.data,
                  success(res) {
                    console.log(res);
                  },
                });
                wx.redirectTo({
                  url: "/pages/login/login",
                });
              }
              // 异步请求到的数据data
            })
            .catch(function (res) {
              console.log(res);
              wx.hideLoading({
                success: (res) => {},
              });
              console.log("第三方登录失败session、wx_token获取失败" + res.errMsg);
            });
        } else {
          that.seyzredirect();
          wx.redirectTo({
            url: "/pages/login/login",
          });
        }
      },
      fail: function (res) {
        wx.hideLoading({
          success: (res) => {},
        });
        wx.showToast({
          title: "小程序需要登录，请点击右下方前往小程序体验",
          icon: "none",
          duration: 1500,
        });
        console.log("登录失败，请求被拒绝！获取用户登录态失败！" + res);
      },
    });
  },
  //初始化语言设置
  initLanguage(data) {
    try {
      wx.setStorageSync("mailLanguage", JSON.stringify(data));
    } catch (e) {
      console.log(e);
    }
    this._getLanguage(data && data.plugin_language ? data.plugin_language : locales);
  },
  gotochecklogin(options) {
    let that = this;
    // let loginFlag = wx.getStorageSync('wx_token');
    // if (loginFlag) {
    that.getfirstData(options);
    // } else {
    // 无skey，作为首次登录
    // that.gotoLogin(options);
    // }
  },
  getfirstData(options) {
    this.globalData.pathData = options.path;
    // this.getInvite();
    // this.initLanguage();
  },

  // 登录 -- 没用到
  // setLoginState: function (cb) {
  //   var that = this;
  //   var _session;
  //   var _wx_token;
  //   console.log("登录中...");
  //   wx.login({
  //     success: function (_json) {
  //       console.log("login登录成功，获取用户info");
  //       wx.getSetting({
  //         success(res) {
  //           if (res.authSetting["scope.userInfo"]) {
  //             // 已经授权，可以直接调用 getUserInfo 获取头像昵称
  //             wx.getUserInfo({
  //               success: function (_info) {
  //                 console.log("code:", _json.code);
  //                 console.log("info:", _info);
  //                 if (_json.code) {
  //                   // 请求登录接口
  //                   that
  //                     .requestServerData(that.getNetAddresss("member.login.index"), "get", {
  //                       code: _json.code,
  //                       info: _info,
  //                       ver: "2",
  //                     })
  //                     .then(function (res) {
  //                       var _data = res.data;
  //                       console.log("登录接口", res);
  //                       if (_data.result == 1) {
  //                         // 存储key
  //                         try {
  //                           wx.setStorageSync("session", _data.msg.session);
  //                         } catch (e) {
  //                           console.log(e);
  //                         }
  //                         // wx.setStorage({
  //                         // 	key: 'session',
  //                         // 	data: _data.msg.session
  //                         // })
  //                         wx.setStorage({
  //                           key: "openid",
  //                           data: _data.data.openid,
  //                         });
  //
  //                         // wx.setStorage({
  //                         // 	key: 'wx_token',
  //                         // 	data: _data.msg.wx_token
  //                         // })
  //                         try {
  //                           wx.setStorageSync("wx_token", _data.msg.wx_token);
  //                         } catch (e) {
  //                           console.log(e);
  //                         }
  //                         wx.setStorage({
  //                           key: "userInfo",
  //                           data: _info,
  //                         });
  //                         wx.setStorage({
  //                           key: "yz_uid",
  //                           data: _data.msg.uid,
  //                         });
  //                         console.log("____uid", _data.msg.uid);
  //                         _session = _data.msg.session;
  //                         _wx_token = _data.msg.wx_token;
  //                         // 设置全局变量session；
  //                         console.log("key 存储成功，登录验证成功，请求数据中2");
  //                         typeof cb == "function" && cb(_session, _wx_token);
  //                       } else {
  //                         console.log(_data.msg);
  //                         wx.showModal({
  //                           title: "提示",
  //                           content: _data.msg,
  //                           success(res) {},
  //                         });
  //                         console.log("第三方登录数据错误" + res.errMsg);
  //                       }
  //                       // 异步请求到的数据data
  //                     })
  //                     .catch(function (res) {
  //                       console.log("第三方登录失败session、wx_token获取失败" + res.errMsg);
  //                     });
  //                 } else {
  //                   console.log("获取用户登录态失败！" + res.errMsg);
  //                 }
  //               },
  //               fail: function (res) {
  //                 console.log("请求被拒绝！获取用户登录态失败！获取用户info失败！" + res);
  //               },
  //             });
  //           } else {
  //             wx.redirectTo({
  //               url: "/pages/login/login",
  //             });
  //           }
  //         },
  //       });
  //     },
  //     fail: function (res) {
  //       console.log("登录失败，请求被拒绝！获取用户登录态失败！" + res);
  //     },
  //   });
  // },
  // 检测登录  -- 没用到
  // getLoginState: function (cb) {
  //   var that = this;
  //   var _session;
  //   var _wx_token;
  //   wx.checkSession({
  //     success: function () {
  //       console.log("登录状态未过期");
  //       // 读取缓存session——key
  //       wx.getStorage({
  //         key: "session",
  //         success: function (res) {
  //           console.log("读取缓存session——key存在", res.data);
  //           _session = res.data;
  //           wx.getStorage({
  //             key: "wx_token",
  //             success: function (res) {
  //               console.log("读取缓存wx_token——key存在", res.data);
  //               _wx_token = res.data;
  //               // that.wx_token = _wx_token
  //               console.log("登录验证成功，请求数据中1");
  //               typeof cb == "function" && cb(_session, _wx_token);
  //             },
  //             fail: function (res) {
  //               console.log("缓存wx_token——！！！！不存在", res);
  //               that.setLoginState(cb);
  //             },
  //           });
  //         },
  //         fail: function (res) {
  //           console.log("缓存session——！！！！不存在", res);
  //           that.setLoginState(cb);
  //         },
  //       });
  //     },
  //     fail: function (res) {
  //       // 登录态过期
  //       console.log("登录态过期", res);
  //       that.setLoginState(cb);
  //     },
  //   });
  // },

  // gotoLogin(options) {
  //   // 没有用到
  //   //接口返回0，并且未登录的情况处理
  //   var that = this;
  //   wx.login({
  //     success: function (_json) {
  //       wx.getSetting({
  //         success(res) {
  //           if (res.authSetting["scope.userInfo"]) {
  //             // 已经授权，可以直接调用 getUserInfo 获取头像昵称
  //             wx.getUserInfo({
  //               success: function (_info) {
  //                 if (_json.code) {
  //                   // 请求登录接口
  //                   that
  //                     .requestServerData(that.getNetAddresss("member.login.index"), "get", {
  //                       code: _json.code,
  //                       info: _info,
  //                       ver: "2",
  //                     })
  //                     .then(function (res) {
  //                       var _data = res.data;
  //                       if (_data.result == 1) {
  //                         // 存储key
  //                         try {
  //                           wx.setStorageSync("session", _data.msg.session);
  //                         } catch (e) {
  //                           console.log(e);
  //                         }
  //                         // wx.setStorage({
  //                         // 	key: 'session',
  //                         // 	data: _data.msg.session
  //                         // })
  //                         wx.setStorage({
  //                           key: "openid",
  //                           data: _data.data.openid,
  //                         });
  //                         try {
  //                           wx.setStorageSync("wx_token", _data.msg.wx_token);
  //                         } catch (e) {
  //                           console.log(e);
  //                         }
  //                         // wx.setStorage({
  //                         // 	key: 'wx_token',
  //                         // 	data: _data.msg.wx_token
  //                         // })
  //                         wx.setStorage({
  //                           key: "userInfo",
  //                           data: _info,
  //                         });
  //                         wx.setStorage({
  //                           key: "yz_uid",
  //                           data: _data.msg.uid,
  //                         });
  //                         that.getfirstData(options);
  //                       } else {
  //                         wx.showModal({
  //                           title: "提示",
  //                           content: _data.msg,
  //                           success(res) {},
  //                         });
  //                       }
  //                       // 异步请求到的数据data
  //                     })
  //                     .catch(function (res) {
  //                       console.log("第三方登录失败session、wx_token获取失败" + res.errMsg);
  //                     });
  //                 } else {
  //                   console.log("获取用户登录态失败！" + res.errMsg);
  //                 }
  //               },
  //               fail: function (res) {
  //                 console.log("请求被拒绝！获取用户登录态失败！获取用户info失败！" + res);
  //               },
  //             });
  //           } else {
  //             wx.redirectTo({
  //               url: "/pages/login/login",
  //             });
  //           }
  //         },
  //       });
  //     },
  //     fail: function (res) {
  //       console.log("登录失败，请求被拒绝！获取用户登录态失败！" + res);
  //     },
  //   });
  // },

  // 腾讯转百度（小程序用这个）
  qqMapTransBMap(lng, lat) {
    if (lng == null || lng == '' || lat == null || lat == '') {
      return {
        lng: Number(lng),
        lat: Number(lat)
      };
    }

    var x_pi = (Math.PI * 3000.0) / 180.0;
    var x = parseFloat(lng);
    var y = parseFloat(lat);
    var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
    var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
    let lng_out = z * Math.cos(theta) + 0.0065;
    let lat_out = z * Math.sin(theta) + 0.006;
    return {
      lng: Number(lng_out),
      lat: Number(lat_out)
    };
  },

  // 百度转腾讯（小程序用这个）
  BMapTransqqMap(lng, lat) {
    if (lng == null || lng == '' || lat == null || lat == '') {
      return {
        lng: Number(lng),
        lat: Number(lat)
      };
    }

    var x_pi = (Math.PI * 3000.0) / 180.0;
    var x = parseFloat(lng) - 0.0065;
    var y = parseFloat(lat) - 0.006;
    var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
    var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
    let lng_out = z * Math.cos(theta);
    let lat_out = z * Math.sin(theta);

    return {
      lng: Number(lng_out),
      lat: Number(lat_out)
    };
  },
  tips(msg, icon = "none", time = 2500) {
    wx.showToast({
      title: msg,
      icon,
      duration: time,
    });
    return false;
  },
  confirm(content, callBack, showCancel = true, confirmText, cancelTextL) {
    // content 弹窗内容,callBack 确认回调,showCancel = true 是否显示取消,confirmText 确认文字,cancelTextL 取消文字
    return new Promise((resolve, reject) => {
      wx.showModal({
        title: '提示',
        content: content,
        showCancel: showCancel,
        confirmText: confirmText || '确认',
        cancelTextL: cancelTextL || '取消',
        success(res) {
          if (res.confirm) {
            resolve(true);
            if (callBack) callBack(true);
          } else if (res.cancel) {
            resolve(false);
            if (callBack) callBack(false);
          }
        },
        fail: () => {
          reject(false);
        }
      });
    });
  },
  setDeliver(_options) {
    let deliverIDStorage = wx.getStorageSync('deliverId') || null; //获取当前会话是否存储了自提点id
    if (_options.query.dyID && !deliverIDStorage) {

      //添加判断sessionStorage是否已存在的目的是防止在其他页面刷新，关联的自提点又变成了链接上的，导致之前手动切换的失效
      let list = ['packageG/index/index', "packageG/newDiy/newDiy"];
      let list_2 = ["packageG/pages/category_v2/category_v2", "packageB/member/category/search_v2/search_v2"];
      if (list_2.indexOf(_options.path) > -1) {
        return false;
      } else if (list.indexOf(_options.path) > -1) {
        wx.setStorageSync("deliverId", _options.query.dyID);
        return false;
      }
      let urlStr = this.getNetAddresss("plugin.package-deliver.frontend.decorate-deliver.getNowPackageDeliver");
      urlStr = urlStr + "&deliver_id=" + _options.query.dyID;
      this._getNetWork({
        url: urlStr,
        success: (resdata) => {
          let res = resdata.data;
          if (res.result == 1) {
            wx.setStorageSync("deliverId", res.data.id);
          }
        }
      });
    }

  },
  shareTimeLine(view) {
    let hasDiyShare = null;
    let shareObject = {};
    let info_config = {}; //获取当前页面的对象
    let value = wx.getStorageSync("yz_uid");
    let mid = null;
    if (value && value != '') {
      mid = value;
    }
    if (view.onShareTimeline) {
      //是否在页面定义配置了onShareTimeline方法；
      hasDiyShare = view.onShareTimeline();
    }
    if (!hasDiyShare) {
      // 有onShareTimeline 但没有没有配置 带上mid
      shareObject.query = `?mid=${mid}`;
      return shareObject;
    } else {
      // 有onShareTimeline 有配置 检查是否有带上mid
      let oldShareFun = view.onShareTimeline; //暂存重写前的分享方法
      view.onShareTimeline = function (e) {
        info_config = oldShareFun();
        if (info_config.query) {
          if (info_config.query.indexOf('mid') > -1) {
            shareObject.query = `${info_config.query}&mid=${mid}`;
          }
        }
        if (info_config.title) {
          shareObject.title = info_config.title;
        }
        if (info_config.imageUrl) shareObject.imageUrl = info_config.imageUrl; //设置分享图片
        return shareObject;
      };
    }
  },
  //设置全局分享
  overShare: function () {
    let that = this;
    // 调用隐藏路由回调
    wx.onAppRoute(function (res) {
      //获取加载的页面
      let pages = getCurrentPages(),
        view = pages[pages.length - 1],
        info_config = {}, //获取当前页面的对象
        hasDiyShare = null;
      // console.log("view.onShareAppMessage=============",view)
      // 浏览足迹  页面切换时更新new_page_comeIn
      that.globalData.new_page_comeIn = 1;
      if (view) {
        try {
          // 分享朋友圈传参全局判断
          that.shareTimeLine(view);
          if (view.onShareAppMessage) {
            //是否在页面定义配置了onShareAppMessage方法；
            hasDiyShare = view.onShareAppMessage();
          }
          if (that.globalData.store_alone_temp == 1 && that.globalData.STORE_ID) {
            that.storeAloneShare(view, info_config,hasDiyShare);
          } else {
            let shareObject = {};
            let value = wx.getStorageSync("yz_uid");
            let mid = null;
            if (value && value != '') {
              mid = value;
            }
            if (hasDiyShare) {
              let oldShareFun = view.onShareAppMessage; //暂存重写前的分享方法
              view.onShareAppMessage = function (e) {
                info_config = oldShareFun();
                if (e && e.from == "button") {
                  return oldShareFun(e);
                }
                value = wx.getStorageSync("yz_uid");
                if (value && value != '') {
                  mid = value;
                }
                //重写分享配置
                // 判断有没有自定义分享path和定义options
                if (info_config.path) {
                  //当前页面有配置path
                  if (info_config.path.indexOf('mid') > -1) {
                    shareObject.path = info_config.path;
                  } else if (mid) {
                    //在当前页有设置其他分享参数但是没有mid
                    if (info_config.path.indexOf('?') > -1) {
                      shareObject.path = `${info_config.path}&mid=${mid}`;
                    } else {
                      shareObject.path = `${info_config.path}?mid=${mid}`;
                    }
                  }
                } else if (mid) {
                  //没有配置，默认带上mid
                  shareObject.path = `/${view.route}?mid=${mid}`;
                }
                // 供应商自提点分享传参 ====== start ==========
                let deliverIDStorage = wx.getStorageSync('deliverId') || null; //获取当前会话是否存储了自提点id
                if (deliverIDStorage) {
                  shareObject.path = `${shareObject.path}&dyID=${deliverIDStorage}`;
                }
                // 供应商自提点分享传参 ====== end ==========

                if (info_config.title) shareObject.title = info_config.title; //设置分享标题
                if (info_config.imageUrl) shareObject.imageUrl = info_config.imageUrl; //设置分享图片
                console.log("重写分享配置", shareObject);
                return shareObject;
              };
            } else {
              // 有onShareAppMessage 但没有没有配置
              view.onShareAppMessage = function (e) {
                value = wx.getStorageSync("yz_uid");
                if (value && value != '') {
                  mid = value;
                }
                shareObject.path = `/${view.route}?mid=${mid}`;
                // console.log(shareObject)
                return shareObject;
              }
            }
          }
          // else if (!info_config) {
          //   //判断页面是否有自定义分享，为空则没配置（感觉不严谨）
          //   view.onShareAppMessage = function () {
          //     //重写分享配置
          //     let value = wx.getStorageSync("yz_uid");
          //     let mid = "";
          //     if (value) {
          //       mid = value;
          //     }
          //     return {
          //       path: `/${view.route}?mid=` + mid,
          //     };
          //   };
          // }
        } catch (error) {
          console.log("app.js报错：error:::页面" + view.route + "获取onShareAppMessage报错=============", error);
        }
      }
    });
  },
  // 企业独立模块分享
  storeAloneShare(view, info_config,hasDiyShare) {
    let shareObject = {};
    let value = wx.getStorageSync("yz_uid");
    let mid = null;
    let STORE_ID = this.globalData.STORE_ID
    if (value && value != '') {
      mid = value;
    }
    if (hasDiyShare) {
      let oldShareFun = view.onShareAppMessage; //暂存重写前的分享方法
      view.onShareAppMessage = function (e) {
        info_config = oldShareFun();
        if (e && e.from == "button") {
          info_config.path = info_config.path+`&store_alone_id=${STORE_ID}`;
          return info_config(e);
        }
        value = wx.getStorageSync("yz_uid");
        if (value && value != '') {
          mid = value;
        }
        //重写分享配置
        // 判断有没有自定义分享path和定义options
        if (info_config.path) {
          //当前页面有配置path
          if (info_config.path.indexOf('mid') > -1) {
            console.log(info_config.path+`&store_alone_id=${STORE_ID}`,'ddddddddddddddd')
            shareObject.path = info_config.path+`&store_alone_id=${STORE_ID}`;
          } else if (mid) {
            //在当前页有设置其他分享参数但是没有mid
            if (info_config.path.indexOf('?') > -1) {
              shareObject.path = `${info_config.path}&mid=${mid}&store_alone_id=${STORE_ID}`;
            } else {
              shareObject.path = `${info_config.path}?mid=${mid}&store_alone_id=${STORE_ID}`;
            }
            console.log(info_config.path+`&store_alone_id=${STORE_ID}`,'ddddddddddddddd22')
          }
        } else if (mid) {
          //没有配置，默认带上mid
          shareObject.path = `/${view.route}?mid=${mid}&store_alone_id=${STORE_ID}`;
          console.log(info_config.path+`&store_alone_id=${STORE_ID}`,'ddddddddddddddd33')
        }

        if (info_config.title) shareObject.title = info_config.title; //设置分享标题
        if (info_config.imageUrl) shareObject.imageUrl = info_config.imageUrl; //设置分享图片
        console.log("重写分享配置", shareObject);
        return shareObject;
      };
    } else {
      // 有onShareAppMessage 但没有没有配置
      view.onShareAppMessage = function (e) {
        value = wx.getStorageSync("yz_uid");
        if (value && value != '') {
          mid = value;
        }
        shareObject.path = `/${view.route}?mid=${mid}&store_alone_id=${STORE_ID}`;
        // console.log(shareObject)
        return shareObject;
      }
    }
    // let value = wx.getStorageSync("yz_uid");
    // let shareObject = {};
    // let mid = "";
    // if (value) {
    //   mid = value;
    // }
    // let objs = Object.keys(info_config);
    // if (objs.length == 0) {
    //   view.onShareAppMessage = ()=> {
    //     return {
    //       path: `/${view.route}?mid=${mid}&store_alone_id=${this.globalData.STORE_ID}`,
    //     };
    //   };
    // } else {
    //   if (info_config.path) {
    //     // 判断有没有自定义分享path和定义options
    //     if (info_config.path.indexOf('?') > -1) {
    //       view.onShareAppMessage = ()=> {
    //         return {
    //           path: `/${view.route}&store_alone_id=${this.globalData.STORE_ID}`,
    //         };
    //       }
    //     } else {
    //       view.onShareAppMessage = ()=> {
    //         return {
    //           path: `/${view.route}?store_alone_id=${this.globalData.STORE_ID}`,
    //         };
    //       }
    //     }
    //   } else {
    //     // 有onShareAppMessage 但没有没有配置
    //     view.onShareAppMessage = function (e) {
    //       value = wx.getStorageSync("yz_uid");
    //       if (value && value != '') {
    //         mid = value;
    //       }
    //       shareObject.path = `/${view.route}?mid=${mid}&store_alone_id=${this.globalData.STORE_ID}`;
    //       return shareObject;
    //     }
    //   }
    // }
  },
  getReverseGeocoder(lat, lng) {
    let that = this;
    return new Promise(function (resolve, reject) {
      if (that.globalData.location && that.globalData.location.latitude == lat && that.globalData.location.longitude == lng) {
        console.log("当前定位位置未发生改变，取globalData里值 》》》》》》》》》》》", that.globalData.location);
        resolve(that.globalData.geocoder);
        return;
      }
      if (!that.globalData.qqmapkey) {
        reject("没有that.globalData.qqmapkey::::", that.globalData.qqmapkey);
        return;
      }
      qqmapsdk = new QQMapWX({
        key: that.globalData.qqmapkey
      });
      qqmapsdk.reverseGeocoder({
        //位置坐标，默认获取当前位置，非必须参数
        location: {
          latitude: lat,
          longitude: lng
        },
        sig: that.globalData.qqmapsig,
        success: function (res) { //成功后的回调
          let mapdata = res.result;
          that.globalData.location = {
            latitude: lat,
            longitude: lng
          };
          that.globalData.geocoder = mapdata;
          console.log("当前定位位置发生改变!!!!!!!重新reverseGeocoder()", that.globalData.location);
          resolve(mapdata);
        },
        fail: function (error) {
          wx.showToast({
            duration: 3000,
            title: error.message,
            icon: 'none'
          });
          reject("app.getReverseGeocoder()报错error::::", error);
        },
        complete: function (res) {

        }
      });
    });
  },
  getGeocoder(address) {
    let that = this;
    // 需要调用次数  没有特殊要求还是不用
    return new Promise(function (resolve, reject) {
      if (!that.globalData.qqmapkey) {
        reject("没有that.globalData.qqmapkey::::", that.globalData.qqmapkey);
        return;
      }
      qqmapsdk = new QQMapWX({
        key: that.globalData.qqmapkey
      });
      qqmapsdk.geocoder({
        //位置坐标，默认获取当前位置，非必须参数
        address: address, //地址参数，例：固定地址
        sig: that.globalData.qqmapsig,
        success: function (res) { //成功后的回调
          let mapdata = res.result;
          let point = {
            lat: mapdata.location.lat,
            lng: mapdata.location.lng
          };
          resolve(point);
        },
        fail: function (error) {
          wx.showToast({
            duration: 3000,
            title: error.message,
            icon: 'none'
          });
          reject("app.getGeocoder()报错error::::", error);
        },
        complete: function (res) {

        }
      });
    });
  },
  resetBasicInfo() {
    //重置yzFirstlogin，使下一次接口重新传参basic_info，获取basic_info数据
    yzFirstlogin = 1;
  },

  watchGlobalData:function(key,method){
    // 解决app.globalData 全局变量更新触发页面及组件更新
    var obj = this.globalData;
    Object.defineProperty(obj,key, {
      configurable: true,
      enumerable: true,
      set: function (value) {
        this.key = value;
        method(value);
      },
      get:function(){
        // 可以在这里打印一些东西，然后在其他界面调用getApp().globalData[key]的时候，这里就会执行。
        return this.key
      }
    })
  },
  adConfig: { // 广告配置
    app_id: newhost.adBrightid||'', // 营销云平台应用ID
    domain: newhost.adBrightDomain||'', // 广告服务域名(同步骤2)
    test_id: '', // 广告位测试ID
    h5_path: '/packageI/web-view/h5View' // H5预览页面
  }
});